package com.spring.sunflower.userinfo;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.android.flexbox.FlexboxLayout;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.makeramen.roundedimageview.RoundedImageView;
import com.spring.sunflower.R;
import com.spring.sunflower.base.BaseActivity;
import com.spring.sunflower.bean.AnchorDetailBean;
import com.spring.sunflower.bean.CityJsonBean;
import com.spring.sunflower.bean.LabelBean;
import com.spring.sunflower.bean.PhotoListBean;
import com.spring.sunflower.bean.STSCertBean;
import com.spring.sunflower.bean.UserInfoUpdateBean;
import com.spring.sunflower.bean.VideoListBean;
import com.spring.sunflower.common.CommonContract;
import com.spring.sunflower.common.FileUploadCallback;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.util.AliUploadUtils;
import com.spring.sunflower.util.AudioUtils;
import com.spring.sunflower.util.DisplayUtils;
import com.spring.sunflower.util.PathUtils;
import com.spring.sunflower.widget.OnBottomSelectListener;
import com.spring.sunflower.widget.UserInfoBirthdayDialog;
import com.spring.sunflower.widget.UserInfoBottomDialog;
import com.spring.sunflower.widget.UserInfoLocationDialog;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Kevin on 2021/6/28<br/>
 * <p>
 * Describe:<br/>
 * 资料编辑页面
 */
public class UserInfoEditActivity extends BaseActivity<UserInfoEditPresenter> implements CommonContract.UserInfoEditView, View.OnClickListener {
    private RoundedImageView ivAvatar;
    private TextView tvVoiceRecordAction, tvVoiceSeconds, tvPictureAction, tvVideoAction,
            tvNickname, tvGender, tvAge, tvHeight, tvWeight, tvLocation, tvSelfIntro, tvEmotion,
            tvJob, tvEducation, tvIncome, tvLabel, tvHouse, tvConstellation, tvAuthStatus;
    private RelativeLayout rlAvatar;
    private TextView tvAvatarChecking;
    private ImageView ivArrowVoice, ivArrowPicture, ivArrowVideo, ivVoicePlay;
    private RecyclerView rvPicture, rvVideo;
    private ProgressBar pbVoice;
    private FlexboxLayout fblHobbyLabel;
    private String userId;
    List<String> dataHeight = new ArrayList<>();
    List<String> dataWeight = new ArrayList<>();
    private ArrayList<CityJsonBean> cityData;
    private List<String> provinceList = new ArrayList<>();
    private List<List<String>> cityDataList = new ArrayList<>();
    private List<LabelBean.DatasBean> dataEmotion, dataJob, dataEducation, dataHouse, dataIncome;
    private List<String> dataEmotionX = new ArrayList<>(),
            dataJobX = new ArrayList<>(),
            dataEducationX = new ArrayList<>(),
            dataHouseX = new ArrayList<>(),
            dataIncomeX = new ArrayList<>();
    private String typeTemp = "";
    private AnchorDetailBean.DatasBean mData;
    private String keyID = "", keySecret = "", securityToken = "";
    private List<AnchorDetailBean.DatasBean.PhotoVOListBean> photoList = new ArrayList<>();
    private List<AnchorDetailBean.DatasBean.VideoDetailVOListBean> videoList = new ArrayList<>();
    private PhotoListAdapter photoAdapter;
    private VideoListAdapter videoListAdapter;
    private AliUploadUtils aliUploadUtils;
    private AudioUtils audioUtils;
    ActivityResultContracts.StartActivityForResult startActivityForResult = new ActivityResultContracts.StartActivityForResult();
    ActivityResultLauncher<Intent> resultLauncher = registerForActivityResult(startActivityForResult, new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            if (data != null) {
                String stringExtra = data.getStringExtra(Constant.USER_NICKNAME);
                tvNickname.setText(stringExtra);
            }
        }
    });
    private List<AnchorDetailBean.DatasBean.HobbiesListBean> hobbiesList;
    private int mHorizontal;
    private int mVertical;
    private UserInfoUpdateBean.DatasBean mVoiceData;
    //    private String voiceSignature;
    private boolean voiceSignaturePlay = false;
    private Timer mRecorderTimer;
    private int mRecorderTime;
    private String voiceSignatureDuration;
    private String voiceSignatureUrl;
    private LabelBean.DatasBean datasBean;
    private boolean voiceVerify = false;

    @Override
    public void initView() {
        tvTitle.setText("个人资料");
        rlAvatar = findViewById(R.id.rlAvatar);
        tvAvatarChecking = findViewById(R.id.tvAvatarChecking);
        ivAvatar = findViewById(R.id.ivAvatar);
        tvAuthStatus = findViewById(R.id.tvAuthStatus);
        tvVoiceRecordAction = findViewById(R.id.tvVoiceRecordAction);
        tvPictureAction = findViewById(R.id.tvPictureAction);
        tvVideoAction = findViewById(R.id.tvVideoAction);
        tvNickname = findViewById(R.id.tvNickname);
        tvGender = findViewById(R.id.tvGender);
        tvAge = findViewById(R.id.tvAge);
        tvConstellation = findViewById(R.id.tvConstellation);
        tvHeight = findViewById(R.id.tvHeight);
        tvWeight = findViewById(R.id.tvWeight);
        tvLocation = findViewById(R.id.tvLocation);
        tvSelfIntro = findViewById(R.id.tvSelfIntro);
        tvEducation = findViewById(R.id.tvEducation);
        tvJob = findViewById(R.id.tvJob);
        tvEmotion = findViewById(R.id.tvEmotion);
        tvIncome = findViewById(R.id.tvIncome);
        tvLabel = findViewById(R.id.tvLabel);
        tvHouse = findViewById(R.id.tvHouse);
        ivArrowVoice = findViewById(R.id.ivArrowVoice);
        ivArrowVideo = findViewById(R.id.ivArrowVideo);
        ivArrowPicture = findViewById(R.id.ivArrowPicture);
        rvVideo = findViewById(R.id.rvVideo);
        rvPicture = findViewById(R.id.rvPicture);
        pbVoice = findViewById(R.id.pbVoice);
        ivVoicePlay = findViewById(R.id.ivVoicePlay);
        tvVoiceSeconds = findViewById(R.id.tvVoiceSeconds);
        fblHobbyLabel = findViewById(R.id.fblHobbyLabel);

        ivAvatar.setOnClickListener(this);
        tvVoiceRecordAction.setOnClickListener(this);
        tvPictureAction.setOnClickListener(this);
        tvVideoAction.setOnClickListener(this);
        tvNickname.setOnClickListener(this);
        tvGender.setOnClickListener(this);
        tvAge.setOnClickListener(this);
        tvHeight.setOnClickListener(this);
        tvWeight.setOnClickListener(this);
        tvLocation.setOnClickListener(this);
        tvSelfIntro.setOnClickListener(this);
        tvEducation.setOnClickListener(this);
        tvJob.setOnClickListener(this);
        tvEmotion.setOnClickListener(this);
        tvIncome.setOnClickListener(this);
        tvLabel.setOnClickListener(this);
        tvHouse.setOnClickListener(this);
        ivArrowVoice.setOnClickListener(this);
        ivArrowVideo.setOnClickListener(this);
        ivArrowPicture.setOnClickListener(this);
        rvVideo.setOnClickListener(this);
        rvPicture.setOnClickListener(this);
        pbVoice.setOnClickListener(this);
        ivVoicePlay.setOnClickListener(this);
        tvAuthStatus.setOnClickListener(this::onClick);
        rlAvatar.setOnClickListener(this::onClick);

        audioUtils = AudioUtils.getInstance();

        userId = getField(Constant.KEY_USERID, "");
        mPresenter.getDetail(userId);
        mPresenter.checkAuth();
        mPresenter.getSTSCert();

        for (int i = 0; i < 50; i++) {
            dataHeight.add((150 + i) + "cm");
        }
        for (int i = 0; i < 60; i++) {
            dataWeight.add((40 + i) + "kg");
        }
        cityData = parseData(getJson(this, "city.json"));
        for (int i = 0; i < cityData.size(); i++) {
            String provinceName = cityData.get(i).getName();
            provinceList.add(provinceName);
            List<CityJsonBean.CityBean> cityList = cityData.get(i).getCityList();
            List<String> arr = new ArrayList<>();
            for (int j = 0; j < cityList.size(); j++) {
                String name = cityList.get(j).getName();
                arr.add(name);
            }
            cityDataList.add(arr);
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        rvPicture.setLayoutManager(gridLayoutManager);
        photoAdapter = new PhotoListAdapter(R.layout.adapter_item_photo_list, photoList);
        rvPicture.setAdapter(photoAdapter);
        GridLayoutManager gridLayoutManagerV = new GridLayoutManager(this, 4);
        rvVideo.setLayoutManager(gridLayoutManagerV);
        videoListAdapter = new VideoListAdapter(R.layout.adapter_item_video_list, videoList);
        rvVideo.setAdapter(videoListAdapter);

        photoAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                goPhotoWallActivity();
            }
        });
        videoListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                goVideoShowListActivity();
            }
        });
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_user_info_edit;
    }

    @Override
    public UserInfoEditPresenter setPresenter() {
        return new UserInfoEditPresenter(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvAuthStatus:
                startNewActivity(AuthRealActivity.class);
                break;
            case R.id.rlAvatar:
            case R.id.ivAvatar:
                if (tvAvatarChecking.isShown()) {
                    showToast("审核中*^_^*");
                    return;
                }
                stopPlayVoice();
                checkOpenGallery(this, true);
//                PictureSelector.create(this)
//                        .openGallery(PictureMimeType.ofImage())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
//                        .imageEngine(GlideEngine.createGlideEngine())
//                        .isWeChatStyle(true)
////                        .theme(themeId)// 主题样式设置 具体参考 values/styles
//                        .maxSelectNum(1)// 最大图片选择数量
//                        .minSelectNum(1)// 最小选择数量
//                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
//                        .isPreviewImage(true)
//                        .isCamera(true)// 是否显示拍照按钮
//                        .isEnableCrop(true)
//                        .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                        .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
//                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
//                        .circleDimmedLayer(false)// 是否圆形裁剪
////                        .showCropFrame(cb_showCropFrame.isChecked())// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
////                        .showCropGrid(cb_showCropGrid.isChecked())// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
////                        .openClickSound(cb_voice.isChecked())// 是否开启点击声音
////                        .selectionMedia(selectList)// 是否传入已选图片
////                        .previewEggs(false)//预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
//                        //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
//                        //.cropCompressQuality(90)// 裁剪压缩质量 默认为100
//                        .minimumCompressSize(100)// 小于100kb的图片不压缩
//                        //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
//                        //.rotateEnabled() // 裁剪是否可旋转图片
//                        //.scaleEnabled()// 裁剪是否可放大缩小图片
//                        //.videoQuality()// 视频录制质量 0 or 1
////                        .videoMaxSecond(11)////显示多少秒以内的视频or音频也可适用
////                        .videoMinSecond(10)
////                        .recordVideoSecond(15)
//                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;
            case R.id.ivArrowVoice:
            case R.id.tvVoiceRecordAction:
                if (voiceSignaturePlay) {
                    audioUtils.pause();
                    voiceSignaturePlay = false;
                    ivVoicePlay.setImageResource(R.drawable.ic_icon_play);
                    mRecorderTimer.cancel();
                }
                if (tvVoiceRecordAction.getText().toString().equals("审核中")) {
                    showToast("审核中*^_^*");
                } else {
                    goVoiceSignActivity();
                }
                break;
            case R.id.ivArrowPicture:
            case R.id.tvPictureAction:
                goPhotoWallActivity();
                break;
            case R.id.ivArrowVideo:
            case R.id.tvVideoAction:
                goVideoShowListActivity();
                break;
            case R.id.tvNickname:
                Intent intent = new Intent(this, NicknameEditActivity.class);
                intent.putExtra(Constant.USER_NICKNAME, tvNickname.getText().toString());
                startActivityForResult(intent, Constant.REQUEST_CODE_NICKNAME);
                break;
            case R.id.tvGender:
                break;
            case R.id.tvAge:
                new XPopup.Builder(this)
                        .enableDrag(true)
                        .asCustom(new UserInfoBirthdayDialog(this, new OnBottomSelectListener() {
                            @Override
                            public void onBottomSelect(String one, String two) {
                                tvAge.setText(one);
                                tvConstellation.setVisibility(View.VISIBLE);
                                tvConstellation.setText(two);
                                HashMap<String, String> map = new HashMap<>();
                                map.put("birthday", one);
                                map.put("constellation", two);
                                mPresenter.updateUserInfo(map);
                            }
                        }))
                        .show();
//                new XPopup.Builder(this)
////                        .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
////                        .enableDrag(true)
////                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
////                        .isThreeDrag(true) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
//                        .asCustom(new ZhihuCommentPopup(this)/*.enableDrag(false)*/)
//                        .show();
                break;
            case R.id.tvHeight:
                new XPopup.Builder(this)
                        .asCustom(new UserInfoBottomDialog(this, dataHeight, new OnBottomSelectListener() {
                            @Override
                            public void onBottomSelect(String one, String two) {
                                tvHeight.setText(two);
                                String substring = two.substring(0, 3);
                                HashMap<String, String> map = new HashMap<>();
                                map.put("height", substring);
                                mPresenter.updateUserInfo(map);
                            }
                        }))
                        .show();

                break;
            case R.id.tvWeight:
                new XPopup.Builder(this)
                        .asCustom(new UserInfoBottomDialog(this, dataWeight, new OnBottomSelectListener() {
                            @Override
                            public void onBottomSelect(String one, String two) {
                                tvWeight.setText(two);
                                String substring = two.substring(0, 2);
                                HashMap<String, String> map = new HashMap<>();
                                map.put("weight", substring);
                                mPresenter.updateUserInfo(map);
                            }
                        }))
                        .show();
                break;
            case R.id.tvLocation:
                new XPopup.Builder(this)
                        .asCustom(new UserInfoLocationDialog(this, provinceList, cityDataList, new OnBottomSelectListener() {
                            @Override
                            public void onBottomSelect(String one, String two) {
//                                showToast(one + "" + two);
                                tvLocation.setText(one + " " + two);
                                HashMap<String, String> map = new HashMap<>();
                                map.put("nativeProvince", one);
                                map.put("nativeCity", two);
                                mPresenter.updateUserInfo(map);
                            }
                        }))
                        .show();
                break;
            case R.id.tvEducation:
                handleEmotionLabel(dataEducation, dataEducationX, Constant.USER_EDUCATION);
                break;
            case R.id.tvSelfIntro:
                Intent intentSelf = new Intent(this, SelfSignatureEditActivity.class);
                intentSelf.putExtra(Constant.USER_SIGNATURE, tvSelfIntro.getText().toString());
                startActivityForResult(intentSelf, Constant.REQUEST_CODE_SELF_INTRO);
                break;
            case R.id.tvJob:
                handleEmotionLabel(dataJob, dataJobX, Constant.USER_JOB);
                break;
            case R.id.tvHouse:
                handleEmotionLabel(dataHouse, dataHouseX, Constant.USER_HOUSE);
                break;
            case R.id.tvEmotion:
                handleEmotionLabel(dataEmotion, dataEmotionX, Constant.USER_EMOTION);
                break;
            case R.id.tvIncome:
                handleEmotionLabel(dataIncome, dataIncomeX, Constant.USER_INCOME);
                break;
            case R.id.tvLabel:
                goHobbyLabelActivity();
                break;
            case R.id.ivVoicePlay:
                if (voiceSignaturePlay) {
                    audioUtils.pause();
                    voiceSignaturePlay = false;
                    ivVoicePlay.setImageResource(R.drawable.ic_icon_play);
                    mRecorderTimer.cancel();
                } else {
                    if (mVoiceData != null) {
                        String voiceSignatureUrl = mVoiceData.getVoiceSignatureUrl();
                        playVoiceSign(voiceSignatureUrl);
                    } else {
                        if (!TextUtils.isEmpty(voiceSignatureUrl)) {
                            playVoiceSign(voiceSignatureUrl);
                        }
                    }
                }
                break;
        }
    }

    private void stopPlayVoice() {
        if (voiceSignaturePlay) {
            audioUtils.stopPlay();
            voiceSignaturePlay = false;
            mRecorderTime = 0;
            mRecorderTimer.cancel();
        }
    }

    private void playVoiceSign(String voiceSignatureUrl) {
        voiceSignaturePlay = true;
        if (mRecorderTime == 0) {
            pbVoice.setProgress(0);
        }
        ivVoicePlay.setImageResource(R.drawable.ic_icon_pause);
        audioUtils.play(voiceSignatureUrl, new AudioUtils.PlayCallBack() {
            @Override
            public void onCompletion(MediaPlayer param1MediaPlayer) {
                voiceSignaturePlay = false;
                ivVoicePlay.setImageResource(R.drawable.ic_icon_play);
                mRecorderTime = 0;
                mRecorderTimer.cancel();
            }

            @Override
            public void onPrepared(MediaPlayer param1MediaPlayer) {

            }
        });
        startTimer();
    }

    private void startTimer() {
//        mRecorderTime = 0;
        mRecorderTimer = new Timer();
        mRecorderTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int progress = (int) ((++mRecorderTime) / Float.valueOf(voiceSignatureDuration) * 100);
                        pbVoice.setProgress(progress);
                        if (String.valueOf(mRecorderTime).equals(voiceSignatureDuration)) {
                            mRecorderTimer.cancel();
                            mRecorderTime = 0;
                        }
                    }
                });
            }
        }, 1000, 1000);
    }

    private void goVoiceSignActivity() {
        stopPlayVoice();
        Intent intent = new Intent(this, VoiceSignActivity.class);
        intent.putExtra(Constant.ALI_KEY_ID, keyID);
        intent.putExtra(Constant.ALI_KEY_SECRET, keySecret);
        intent.putExtra(Constant.ALI_SECURITY_TOKEN, securityToken);
        startActivityForResult(intent, Constant.REQUEST_CODE_VOICE);
    }

    private void goHobbyLabelActivity() {
        stopPlayVoice();
        Intent intent = new Intent(this, HobbyLabelActivity.class);
        intent.putExtra(Constant.USER_HOBBY_LABEL, (Serializable) hobbiesList);
        startActivityForResult(intent, Constant.REQUEST_CODE_HOBBY_LABEL);
    }

    private void goVideoShowListActivity() {
        stopPlayVoice();
        Intent intentVideo = new Intent(this, VideoShowListActivity.class);
        intentVideo.putExtra(Constant.ALI_KEY_ID, keyID);
        intentVideo.putExtra(Constant.ALI_KEY_SECRET, keySecret);
        intentVideo.putExtra(Constant.ALI_SECURITY_TOKEN, securityToken);
        startActivityForResult(intentVideo, Constant.REQUEST_CODE_VIDEO_LIST);
    }

    private void goPhotoWallActivity() {
        stopPlayVoice();
        Intent intentPic = new Intent(this, PhotoWallActivity.class);
        intentPic.putExtra(Constant.ALI_KEY_ID, keyID);
        intentPic.putExtra(Constant.ALI_KEY_SECRET, keySecret);
        intentPic.putExtra(Constant.ALI_SECURITY_TOKEN, securityToken);
        startActivityForResult(intentPic, Constant.REQUEST_CODE_PHOTO_LIST);
    }

    private void handleEmotionLabel(List<LabelBean.DatasBean> dataJob, List<String> dataJobX, String userJob) {
        if (dataJob == null) {
            mPresenter.getLabel(userJob);
        } else {
            showPopupView(dataJob, dataJobX, userJob).show();
        }
    }

    @Override
    public void showData(AnchorDetailBean.DatasBean data) {
        mData = data;
        AnchorDetailBean.DatasBean.VerifyVOBean verifyVO = data.getVerifyVO();
        String authenticate = data.getAuthenticate();
        GradientDrawable tvAuthStatusBackground = (GradientDrawable) tvAuthStatus.getBackground();
        if ("1".equals(authenticate)) {
            tvAuthStatus.setText("认证成功");
            tvAuthStatusBackground.setColor(Color.TRANSPARENT);
        } else {
//            tvAuthStatus.setText("照片未认证");
//            tvAuthStatusBackground.setColor(Color.TRANSPARENT);
        }
        Boolean photoHasVerify = verifyVO.getPhotoHasVerify();
        tvAvatarChecking.setVisibility(photoHasVerify ? View.VISIBLE : View.GONE);
        String photo = verifyVO.getPhoto();
        if (!TextUtils.isEmpty(photo)) {
            Glide.with(this).
                    load(photo)
                    .into(ivAvatar);
        } else {
            Glide.with(this).
                    load(data.getPhoto())
                    .into(ivAvatar);
        }
//        voiceSignature = data.getVoiceSignature();
        voiceSignatureUrl = verifyVO.getVoiceSignatureUrl();
        Boolean voiceSignatureHasVerify = verifyVO.getVoiceSignatureHasVerify();
        voiceVerify = voiceSignatureHasVerify;
        if (!TextUtils.isEmpty(voiceSignatureUrl) && voiceSignatureHasVerify) {
            ivVoicePlay.setColorFilter(getColorX(R.color.colorPrimary));
            pbVoice.setProgress(100);
            voiceSignatureDuration = verifyVO.getVoiceSignatureDuration();
            tvVoiceSeconds.setText(voiceSignatureDuration + "''");
            tvVoiceSeconds.setVisibility(View.VISIBLE);
            tvVoiceRecordAction.setText(voiceSignatureHasVerify ? "审核中" : "重新录制");
            tvVoiceRecordAction.setTextColor(voiceSignatureHasVerify ? getColorX(R.color.red_1) : getColorX(R.color.colorPrimary));
        } else if (!voiceSignatureHasVerify && !TextUtils.isEmpty(data.getVoiceSignature())) {
            voiceSignatureUrl = data.getVoiceSignature();
            ivVoicePlay.setColorFilter(getColorX(R.color.colorPrimary));
            pbVoice.setProgress(100);
            voiceSignatureDuration = verifyVO.getVoiceSignatureDuration();
            tvVoiceSeconds.setText(data.getVoiceSignatureDuration() + "''");
            tvVoiceSeconds.setVisibility(View.VISIBLE);
            tvVoiceRecordAction.setText("重新录制");
            tvVoiceRecordAction.setTextColor(getColorX(R.color.colorPrimary));
        } else {
            tvVoiceSeconds.setVisibility(View.INVISIBLE);
        }
        tvNickname.setText(data.getNickname());
        String sex = data.getSex();
        if (TextUtils.isEmpty(sex)) {
            tvGender.setText("男");
        } else {
            tvGender.setText("1".equals(sex) ? "男" : "女");
        }
        Date date = TimeUtils.millis2Date(Long.valueOf(data.getBirthday()));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DATE);
        String zodiac = TimeUtils.getZodiac(Long.valueOf(data.getBirthday()));
        tvConstellation.setText(zodiac);
        tvAge.setText(TimeUtils.millis2String(Long.valueOf(data.getBirthday()), new SimpleDateFormat("yyyy-MM-dd")));
        handleTextLabel(data.getHeight(), tvHeight, "cm");
        handleTextLabel(data.getWeight(), tvWeight, "kg");
        handleTextLabel(data.getNativeProvince() + " " + data.getNativeCity(), tvLocation);
        handleTextLabel(data.getSignature(), tvSelfIntro);
        if (data.getMaritalStatusV().size() > 0) {
            handleTextLabel(data.getMaritalStatusV().get(0).getName(), tvEmotion);
        } else {
            handleTextLabelEmpty(tvEmotion);
        }
        if (data.getEducationV().size() > 0) {
            handleTextLabel(data.getEducationV().get(0).getName(), tvEducation);
        } else {
            handleTextLabelEmpty(tvEducation);
        }
        if (data.getOccupationV().size() > 0) {
            handleTextLabel(data.getOccupationV().get(0).getName(), tvJob);
        } else {
            handleTextLabelEmpty(tvJob);
        }
        if (data.getIncomeV().size() > 0) {
            handleTextLabel(data.getIncomeV().get(0).getName(), tvIncome);
        } else {
            handleTextLabelEmpty(tvIncome);
        }
        if (data.getHousingV().size() > 0) {
            handleTextLabel(data.getHousingV().get(0).getName(), tvHouse);
        } else {
            handleTextLabelEmpty(tvHouse);
        }
        if (data.getHobbiesList().size() > 0) {
            tvLabel.setText("编辑");
            tvLabel.setTextColor(getColorX(R.color.gray_6));
        } else {
            handleTextLabelEmpty(tvLabel);
        }
        List<AnchorDetailBean.DatasBean.PhotoVOListBean> photoVOList = data.getPhotoVOList();
        Collections.reverse(photoVOList);
        photoAdapter.addData(photoVOList);
        if (photoVOList.size() < 8) {
            AnchorDetailBean.DatasBean.PhotoVOListBean bean = new AnchorDetailBean.DatasBean.PhotoVOListBean();
            bean.setPlaceHolder(true);
            photoAdapter.addData(bean);
        }
        List<AnchorDetailBean.DatasBean.VideoDetailVOListBean> videoDetailVOList = data.getVideoDetailVOList();
        Collections.reverse(videoDetailVOList);
        videoListAdapter.addData(videoDetailVOList);
        if (videoDetailVOList.size() < 8) {
            AnchorDetailBean.DatasBean.VideoDetailVOListBean videoDetailVOListBean = new AnchorDetailBean.DatasBean.VideoDetailVOListBean();
            videoDetailVOListBean.setPlaceHolder(true);
            videoListAdapter.addData(videoDetailVOListBean);
        }
        hobbiesList = data.getHobbiesList();
        mHorizontal = DisplayUtils.dpTpx(this, 10);
        mVertical = DisplayUtils.dpTpx(this, 3);
        for (int i = 0; i < hobbiesList.size(); i++) {
            TextView textView = new TextView(this);
            textView.setTextColor(getColorX(R.color.white));
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-2, -2);
            lp.setMargins(mHorizontal, 0, 0, 0);
            textView.setLayoutParams(lp);
            textView.setPadding(mHorizontal, mVertical, mHorizontal, mVertical);
            textView.setBackground(getDrawable(R.drawable.ic_btn_bg_click_disable));
            GradientDrawable background = (GradientDrawable) textView.getBackground();
            background.setColor(Color.parseColor("#" + hobbiesList.get(i).getColor()));
            textView.setText(hobbiesList.get(i).getName());
            textView.setTextSize(12);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    goHobbyLabelActivity();
                }
            });
            fblHobbyLabel.addView(textView);
        }
    }

    private void handleTextLabel(String value, TextView tv, String suffix) {
        if (TextUtils.isEmpty(value) || "0".equals(value)) {
            handleTextLabelEmpty(tv);
        } else {
            tv.setText(value + suffix);
            tv.setTextColor(getColorX(R.color.gray_6));
        }
    }

    private void handleTextLabel(String value, TextView tv) {
        handleTextLabel(value, tv, "");
    }

    private void handleTextLabelEmpty(TextView tv) {
        tv.setText("待完善");
        tv.setTextColor(getColorX(R.color.colorPrimary));
    }

    @Override
    public void realAuth(boolean b) {

    }

    @Override
    public void personInfoFinish(boolean b) {

    }

    @Override
    public void showLabelData(List<LabelBean.DatasBean> data, String type) {
        List<String> tempList = new ArrayList<>();
        switch (type) {
            case Constant.USER_EDUCATION:
                dataEducation = data;
                for (LabelBean.DatasBean bean : data) {
                    dataEducationX.add(bean.getName());
                }
                tempList = dataEducationX;
                break;
            case Constant.USER_EMOTION:
                dataEmotion = data;
                for (LabelBean.DatasBean bean : data) {
                    dataEmotionX.add(bean.getName());
                }
                tempList = dataEmotionX;
                break;
            case Constant.USER_JOB:
                dataJob = data;
                for (LabelBean.DatasBean bean : data) {
                    dataJobX.add(bean.getName());
                }
                tempList = dataJobX;
                break;
            case Constant.USER_HOUSE:
                dataHouse = data;
                for (LabelBean.DatasBean bean : data) {
                    dataHouseX.add(bean.getName());
                }
                tempList = dataHouseX;
                break;
            case Constant.USER_INCOME:
                dataIncome = data;
                for (LabelBean.DatasBean bean : data) {
                    dataIncomeX.add(bean.getName());
                }
                tempList = dataIncomeX;
                break;
            case Constant.USER_HOBBIES:
                break;
        }
        BasePopupView popupView = showPopupView(data, tempList, type);
        popupView.show();
    }

    @Override
    public void updateSuccess(UserInfoUpdateBean.DatasBean data) {
        showToast("更新成功");
    }

    @Override
    public void updateSuccess(UserInfoUpdateBean.DatasBean data, boolean updateAvatar) {
        showToast("更新成功");
        Glide.with(this).
                load(data.getPhoto())
                .into(ivAvatar);
        tvAvatarChecking.setVisibility(data.getPhotoHasVerify() ? View.VISIBLE : View.GONE);

    }

    private BasePopupView showPopupView(List<LabelBean.DatasBean> data, List<String> dataX, String type) {
        BasePopupView basePopupView = new XPopup.Builder(this)
                .asCustom(new UserInfoBottomDialog(this, dataX, new OnBottomSelectListener() {
                    @Override
                    public void onBottomSelect(String one, String two) {
                        switch (type) {
                            case Constant.USER_EDUCATION:
                                dataEducation = data;
                                processEmotionLabelSetting(one, two, type, tvEducation, data);
                                break;
                            case Constant.USER_EMOTION:
                                dataEmotion = data;
                                processEmotionLabelSetting(one, two, type, tvEmotion, data);
                                break;
                            case Constant.USER_JOB:
                                dataJob = data;
                                processEmotionLabelSetting(one, two, type, tvJob, data);
                                break;
                            case Constant.USER_HOUSE:
                                dataHouse = data;
                                processEmotionLabelSetting(one, two, type, tvHouse, data);
                                break;
                            case Constant.USER_INCOME:
                                dataIncome = data;
                                processEmotionLabelSetting(one, two, type, tvIncome, data);
                                break;
                            case Constant.USER_HOBBIES:
                                break;
                        }
                    }
                }));
        return basePopupView;
    }

    private void processEmotionLabelSetting(String one, String two, String type, TextView tv, List<LabelBean.DatasBean> data) {
        tv.setText(two);
        tv.setTextColor(getColorX(R.color.gray_6));
        String id = data.get(Integer.valueOf(one)).getId();
        HashMap<String, String> map = new HashMap<>();
        map.put(type, id);
        mPresenter.updateUserInfo(map);
        typeTemp = type;
    }

    @Override
    public void updateFailed() {
        if (typeTemp != "") {
            switch (typeTemp) {
                case Constant.USER_EDUCATION:
                    if (mData.getEducationV().size() > 0) {
                        handleTextLabel(mData.getEducationV().get(0).getName(), tvEducation);
                    } else {
                        handleTextLabelEmpty(tvEducation);
                    }
                    break;
                case Constant.USER_EMOTION:
                    if (mData.getMaritalStatusV().size() > 0) {
                        handleTextLabel(mData.getMaritalStatusV().get(0).getName(), tvEmotion);
                    } else {
                        handleTextLabelEmpty(tvEmotion);
                    }
                    break;
                case Constant.USER_JOB:
                    if (mData.getOccupationV().size() > 0) {
                        handleTextLabel(mData.getOccupationV().get(0).getName(), tvJob);
                    } else {
                        handleTextLabelEmpty(tvJob);
                    }
                    break;
                case Constant.USER_HOUSE:
                    if (mData.getHousingV().size() > 0) {
                        handleTextLabel(mData.getHousingV().get(0).getName(), tvHouse);
                    } else {
                        handleTextLabelEmpty(tvHouse);
                    }
                    break;
                case Constant.USER_INCOME:
                    if (mData.getIncomeV().size() > 0) {
                        handleTextLabel(mData.getIncomeV().get(0).getName(), tvIncome);
                    } else {
                        handleTextLabelEmpty(tvIncome);
                    }
                    break;
            }
            showToast("更新失败:(");
        }
    }

    @Override
    public void loadSTSCert(STSCertBean.DatasBean data) {
        keyID = data.getAccessKeyId();
        keySecret = data.getAccessKeySecret();
        securityToken = data.getSecurityToken();
        aliUploadUtils = AliUploadUtils.getInstance(keyID, keySecret, securityToken);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    if (data != null) {
                        showLoading();
                        List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                        LocalMedia localMedia1 = localMedia.get(0);
                        String path = localMedia1.getPath();
//                        showToast("path=" + path);
                        int cropImageWidth = localMedia1.getCropImageWidth();
                        int cropImageHeight = localMedia1.getCropImageHeight();
                        int width = localMedia1.getWidth();
                        int height = localMedia1.getHeight();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            path = PathUtils.getPath(UserInfoEditActivity.this, Uri.parse(path));
                        }
                        if (localMedia1.isCut()) {
                            path = localMedia1.getCutPath();
                        }
                        if (aliUploadUtils != null) {
                            aliUploadUtils.upLoadFile(path, new FileUploadCallback() {
                                @Override
                                public void onFailure(String str) {
                                    hideLoading();
                                    showToast(str);
                                }

                                @Override
                                public void onSuccess(Object paramRequestString, String filePath) {
//                                    showToast("filePath=" + filePath);
                                    HashMap<String, String> map = new HashMap<>();
                                    map.put("photo", filePath);
                                    mPresenter.updateUserInfo(map, true);
                                }

                                @Override
                                public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                                    printD("progress=" + currentSize * 1.0 / totalSize);
                                }
                            });
                        }
                    }

                    break;
                case Constant.REQUEST_CODE_NICKNAME:
                    if (data != null) {
                        String stringExtra = data.getStringExtra(Constant.USER_NICKNAME);
                        tvNickname.setText(stringExtra);
                    }
                    break;
                case Constant.REQUEST_CODE_SELF_INTRO:
                    if (data != null) {
                        String stringExtra = data.getStringExtra(Constant.USER_SIGNATURE);
                        tvSelfIntro.setText(stringExtra);
                    }
                    break;
                case Constant.REQUEST_CODE_PHOTO_LIST:
                    if (data != null) {
                        List<AnchorDetailBean.DatasBean.PhotoVOListBean> photoListTemp = new ArrayList<>();
                        List<PhotoListBean.DatasBean> list = (List<PhotoListBean.DatasBean>) data.getSerializableExtra(Constant.USER_PHOTO_LIST);
                        for (PhotoListBean.DatasBean bean : list) {
                            AnchorDetailBean.DatasBean.PhotoVOListBean listBean = new AnchorDetailBean.DatasBean.PhotoVOListBean();
                            listBean.setCreateTime(bean.getCreateTime());
                            listBean.setHeight(bean.getHeight());
                            listBean.setId(bean.getId());
                            listBean.setIsVerify(bean.getIsVerify());
                            listBean.setMemberId(bean.getMemberId());
                            listBean.setPhotoPath(bean.getPhotoPath());
                            listBean.setWidth(bean.getWidth());
                            listBean.setPlaceHolder(bean.isPlaceHolder());
                            photoListTemp.add(listBean);
                        }
                        photoAdapter.setNewInstance(photoListTemp);
                    }
                    break;
                case Constant.REQUEST_CODE_VIDEO_LIST:
                    if (data != null) {
                        List<AnchorDetailBean.DatasBean.VideoDetailVOListBean> videoListTemp = new ArrayList<>();
                        List<VideoListBean.DatasBean> list = (List<VideoListBean.DatasBean>) data.getSerializableExtra(Constant.USER_VIDEO_LIST);
                        for (VideoListBean.DatasBean bean : list) {
                            AnchorDetailBean.DatasBean.VideoDetailVOListBean listBean = new AnchorDetailBean.DatasBean.VideoDetailVOListBean();
                            listBean.setId(bean.getId());
                            listBean.setIsVerify(bean.getIsVerify());
                            listBean.setMemberId(bean.getMemberId());
                            listBean.setPlaceHolder(bean.isPlaceHolder());
                            listBean.setBrowseTotal(bean.getBrowseTotal());
                            listBean.setCity(bean.getCity());
                            listBean.setCommentTotal(bean.getCommentTotal());
                            listBean.setLikeTotal(bean.getLikeTotal());
                            listBean.setDescribe(bean.getDescribe());
                            listBean.setIsVerify(bean.getIsVerify());
                            listBean.setVideoFirstPhotoUrl(bean.getVideoFirstPhotoUrl());
                            listBean.setVideoPath(bean.getVideoPath());
                            videoListTemp.add(listBean);
                        }
                        videoListAdapter.setNewInstance(videoListTemp);
                    }
                    break;
                case Constant.REQUEST_CODE_HOBBY_LABEL:
                    if (data != null) {
                        List<LabelBean.DatasBean> list = (List<LabelBean.DatasBean>) data.getSerializableExtra(Constant.USER_HOBBY_LABEL);
                        fblHobbyLabel.removeAllViews();
                        hobbiesList.clear();
                        for (int i = 0; i < list.size(); i++) {
                            TextView textView = new TextView(this);
                            textView.setTextColor(getColorX(R.color.white));
                            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-2, -2);
                            lp.setMargins(mHorizontal, 0, 0, 0);
                            textView.setLayoutParams(lp);
                            textView.setPadding(mHorizontal, mVertical, mHorizontal, mVertical);
                            textView.setBackground(getDrawable(R.drawable.ic_btn_bg_click_disable));
                            GradientDrawable background = (GradientDrawable) textView.getBackground();
                            background.setColor(Color.parseColor("#" + list.get(i).getColor()));
                            textView.setText(list.get(i).getName());
                            textView.setTextSize(12);
                            textView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    goHobbyLabelActivity();
                                }
                            });
                            fblHobbyLabel.addView(textView);
                            AnchorDetailBean.DatasBean.HobbiesListBean bean = new AnchorDetailBean.DatasBean.HobbiesListBean();
                            datasBean = list.get(i);
                            bean.setColor(datasBean.getColor());
                            bean.setId(datasBean.getId());
                            bean.setName(datasBean.getName());
                            bean.setType(datasBean.getType());
                            bean.setOrderId(datasBean.getOrderId());
                            hobbiesList.add(bean);
                        }
                    }
                    break;
                case Constant.REQUEST_CODE_VOICE:
                    if (data != null) {
                        mVoiceData = (UserInfoUpdateBean.DatasBean) data.getSerializableExtra(Constant.USER_VOICE_SIGN);
                        ivVoicePlay.setColorFilter(getColorX(R.color.colorPrimary));
                        pbVoice.setProgress(100);
                        voiceSignatureDuration = mVoiceData.getVoiceSignatureDuration();
                        tvVoiceSeconds.setText(voiceSignatureDuration + "''");
                        tvVoiceSeconds.setVisibility(View.VISIBLE);
                        Boolean voiceSignatureHasVerify = mVoiceData.getVoiceSignatureHasVerify();
                        tvVoiceRecordAction.setText(voiceSignatureHasVerify ? "审核中" : "重新录制");
                        tvVoiceRecordAction.setTextColor(voiceSignatureHasVerify ? getColorX(R.color.red_1) : getColorX(R.color.colorPrimary));
                    }
                    break;
            }
        }
    }

    public String getJson(Context paramContext, String paramString) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(paramContext.getAssets().open(paramString)));
            while (true) {
                paramString = bufferedReader.readLine();
                if (paramString != null) {
                    stringBuilder.append(paramString);
                    continue;
                }
                break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public ArrayList<CityJsonBean> parseData(String paramString) {
        ArrayList arrayList = new ArrayList();
        try {
            JSONArray jSONArray = new JSONArray(paramString);
            Gson gson = new Gson();
            for (byte b = 0; b < jSONArray.length(); b++)
                arrayList.add((CityJsonBean) gson.fromJson(jSONArray.optJSONObject(b).toString(), CityJsonBean.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arrayList;
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopPlayVoice();
    }
}
